﻿#region

using System;
using System.Web;
using System.Web.SessionState;

#endregion

namespace BuildMotion.MotionTracker.Web.Common
{
    public class MotionTrackerModule : IHttpModule, IRequiresSessionState 
    {
        private HttpApplication application = null;
        private HttpRequest request = null;
        private HttpSessionState session = null;
        private Guid trackerId = Guid.Empty;

        #region IHttpModule Members

        /// <summary>
        /// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
        /// </summary>
        public void Dispose()
        {
            ; // throw new System.NotImplementedException();
        }

        /// <summary>
        /// Initializes a module and prepares it to handle requests.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += new EventHandler(contextPreRequestHandlerExecute);
            this.application = context;
        }

        #endregion

        /// <summary>
        /// Handles the PreRequestHandlerExecute event of the context control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void contextPreRequestHandlerExecute(object sender, EventArgs e)
        {
            //if (this is IRequiresSessionState || this is IReadOnlySessionState)
            //{
            //    MotionTrackerService.TrackRequest(this.application);
            //    string appName = MotionTrackerService.GetApplicationName();
            //}

            /*
             Cannot use the Application object here. Is not serializable with WCF.
             */
            // Update to use the proxy;
            //MotionTrackerWCFServiceClient proxy = MotionTrackerServiceProxy.GetMotionTrackerProxy();
            //proxy.TrackRequest(this.application);
            this.session = this.application.Session;
            MotionTrackerService.TrackRequest(this.application, System.Guid.NewGuid(), Guid.NewGuid());
        }
    }
}